using UnityEngine;
using UnityEngine.UI;

public class ShopManager : MonoBehaviour
{
    public GameObject shopItemPrefab;
    public LootSystem lootSystem;
    public Player player;
    public Transform itemParent;
    public ItemManager itemManager;
    public int itemCount = 10;
    private System.Random random = new System.Random();
    private int itemsPerRow = 5;

    private void Start()
    {
        if (lootSystem == null) lootSystem = FindObjectOfType<LootSystem>();
        if (player == null) player = FindObjectOfType<Player>();
        if (itemManager == null) itemManager = FindObjectOfType<ItemManager>();
        GenerateShopItems();
    }

    private void GenerateShopItems()
    {
        foreach (Transform child in itemParent) Destroy(child.gameObject);

        for (int i = 0; i < itemCount; i++)
        {
            Item randomItem = lootSystem.GenerateShopLoot((int)player.stats.distortionLevel);
            if (randomItem == null) continue;

            GameObject itemInstance = Instantiate(shopItemPrefab, itemParent);
            int row = i / itemsPerRow;
            int column = i % itemsPerRow;
            itemInstance.transform.localPosition = new Vector3(column * 2.0f - ((itemsPerRow - 1) * 1.0f), -row * 2.5f, 0);

            ShopItemInteractor interactor = itemInstance.AddComponent<ShopItemInteractor>();
            interactor.itemData = randomItem;
            interactor.player = player;

            SpriteRenderer renderer = itemInstance.GetComponent<SpriteRenderer>();
            if (renderer != null) renderer.sprite = randomItem.icon;

            GameObject priceTag = new GameObject("PriceTag");
            priceTag.transform.SetParent(itemInstance.transform);
            priceTag.transform.localPosition = new Vector3(0, -1.0f, 0);

            Text priceText = priceTag.AddComponent<Text>();
            priceText.text = $"{randomItem.SalePrice} 金币";
            priceText.fontSize = 14; // 使用合适的字体大小
            priceText.alignment = TextAnchor.MiddleCenter; // 设置文本居中对齐

            // 设置字体等属性
            Font font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            priceText.color = Color.black;
        }
    }
}
